package com.hr.mes.controller;

import com.hr.mes.dto.Page;
import com.hr.mes.dto.Result;
import com.hr.mes.entity.User;
import com.hr.mes.enums.MyExceptionEnum;
import com.hr.mes.exception.MyException;
import com.hr.mes.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户管理")
@CrossOrigin
@RequestMapping("/api/user")
@RestController()
public class UserController {

    @Autowired
    private UserService userService;

    @RequiresRoles("admin")
    @ApiOperation("新增用户")
    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user){
        try{
            userService.addUser(user);
            return Result.ok();
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.USER_ADD_ERROR, e);
        }
    }

    @RequiresRoles("admin")
    @ApiOperation("删除用户")
    @GetMapping("/deleteUser")
    public Result deleteUser(@RequestParam Integer userId){
        try{
            userService.deleteUser(userId);
            return Result.ok();
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.USER_DELETE_ERROR, e);
        }
    }

    @RequiresRoles("admin")
    @ApiOperation("更新用户")
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        try{
            userService.updateUser(user);
            return Result.ok();
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.USER_UPDATE_ERROR, e);
        }
    }

    @RequiresPermissions("user:view")
    @ApiOperation("查询一个用户")
    @GetMapping("/getUserByUserId")
    public Result getUserByUserId(@RequestParam Integer userId){
        try{
            User user = userService.getUser(userId);
            return Result.ok(user);
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.USER_VIEW_ERROR, e);
        }
    }

    @RequiresRoles("admin")
    @ApiOperation("查询用户列表")
    @GetMapping("/getUserPage")
    public Result getUserPage(@RequestParam Integer pageNo, @RequestParam Integer pageSize){
        try{
            Page<User> page = userService.getUserPage(pageNo, pageSize);
            return Result.ok(page);
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.USER_VIEW_ERROR, e);
        }
    }

    @RequiresPermissions("user:view")
    @ApiOperation("查询用户列表")
    @GetMapping("/getUserList")
    public Result getUserList(){
        try{
            List<User> userList = userService.getUserList();
            return Result.ok(userList);
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.USER_VIEW_ERROR, e);
        }
    }

}
